package com.atguigu.gulimall.ware.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.Exchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author : Jungle
 * @Description :
 */
@Configuration
public class MyRabbitConfig {
    /**
     * 使用JsoN序列化机制,进行消息转换
     */
    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    ///**
    // * 当用Bean创建队列的时候有时候不能创建出来，配置一个监听，再启动其他都会可以创建成功
    // */
    //@RabbitListener(queues = "stock.release.stock.queue")
    //public void handle(Message message){
    //
    //}

    @Bean
    public Exchange stockEventExchange() {
        return new TopicExchange("stock-event-exchange", true, false);
    }

    /**
     * 普通队列，不需要参数
     */
    @Bean
    public Queue stockReleaseStockQueue() {
        // boolean exclusive 排他，只能一个人连接
        //String name, boolean durable, boolean exclusive, boolean autoDelete, Map<String, Object> arguments
        return new Queue("stock.release.stock.queue", true, false, false);
    }

    /**
     * boolean exclusive 排他，只能一个人连接
     * String name, boolean durable, boolean exclusive, boolean autoDelete, Map<String, Object> arguments
     * 延迟队列
     * x-dead-letter-exchange: order-event-exchange
     * x-dead-letter-routing-key : order.release.order
     * x-message-ttl: 60000
     */
    @Bean
    public Queue stockDelayQueue() {
        Map<String, Object> arguments = new HashMap<>();
        //信死了交给哪个交换机
        arguments.put("x-dead-letter-exchange", "stock-event-exchange");
        arguments.put("x-dead-letter-routing-key", "stock.release");
        arguments.put("x-message-ttl", 120000);
        return new Queue("stock.delay.queue", true, false, false, arguments);
    }


    /**
     * 交换机和普通队列的绑定关系
     */
    @Bean
    public Binding stockReleaseBinding() {
        //String destination, DestinationType destinationType, String exchange, String routingKey,Map<String, Object> arguments
        return new Binding("stock.release.stock.queue",
                Binding.DestinationType.QUEUE, "stock-event-exchange", "stock.release.#", null);

    }

    /**
     * 交换机和延迟队列的绑定关系
     */
    @Bean
    public Binding stockLockedBinding() {
        //String destination, DestinationType destinationType, String exchange, String routingKey,Map<String, Object> arguments
        return new Binding("stock.delay.queue",
                Binding.DestinationType.QUEUE, "stock-event-exchange", "stock.locked", null);

    }
}
